package edu.univercidade.tcc.sap.server;

import javax.naming.NamingException;

import edu.univercidade.tcc.sap.client.UserService;
import edu.univercidade.tcc.sap.ejb.UserServiceLocal;
import edu.univercidade.tcc.sap.model.User;

public class UserServlet extends SAPServiceServlet implements UserService {

	private static final long serialVersionUID = -278721241299982367L;
	private UserServiceLocal userService;
	private static final String USER_ATTR = "user";

	public UserServlet() throws NamingException {
		super();
		userService = ejbFind(UserServiceLocal.class);
	}

	public boolean isValidUser(String user, String password) {
		if (null != this.getThreadLocalRequest().getSession()
				.getAttribute(USER_ATTR)) {
			return true;
		}

		boolean isValid = userService.isValidUser(user, password);
		if (isValid) {
			this.getThreadLocalRequest().getSession()
					.setAttribute(USER_ATTR, user);
		}
		return isValid;
	}

	public User[] activeUsers() {
		return userService.listValid();
	}

	@Override
	public User createUser(String login, String password, String firstname,
			String lastname, String email) {
		return userService.createUser(login, password, firstname, lastname,
				email);
	}

	@Override
	public User createUser(User user) {
		return userService.create(user);
	}
	
	@Override
	public void deleteUser(User user) {
		userService.delete(user);
	}

	@Override
	public void updateUser(User user) {
		userService.update(user);
	}

	@Override
	public String loggedUser() {
		String result = (String) this.getThreadLocalRequest().getSession()
				.getAttribute(USER_ATTR);
		if (null == result)
			throw new IllegalStateException();
		return result;
	}

}
